<?php namespace App\Http\Services;

use App\ActiveParty;
use App\Activity;
use App\ActivityBrowseRecord;
use App\ActivityJoin;
use App\Admin;
use App\AppointExpert;
use App\Classify;
use App\Comment;
use App\CommentLike;
use App\DemandButt;
use App\Demands;
use App\ExpertLabel;
use App\ExpertQualificationImg;
use App\Experts;
use App\Files;
use App\Images;
use App\InvoiceRecord;
use App\Message;
use App\MessageRemind;
use App\PersonalAuth;
use App\UnitAuth;
use App\UnitBindVipPackage;
use App\UnitBusinessLabel;
use App\UnitGrade;
use App\Units;
use App\User;
use App\UserAttentionActivity;
use App\UserAttentionDemand;
use App\UserAttentionNews;
use App\UserInfo;
use App\UserXUnit;
use App\VipInfo;
use App\VipPackage;
use App\VipPackageXRule;
use App\VipRule;
use Carbon\Carbon;
use Auth;
use Intervention\Image\Facades\Image;
use phpDocumentor\Reflection\Types\Self_;

class CommonManager
{

    /**
     * 获取用户的基本信息
     * @param $user_id
     * @return array|null
     */
    public static function getUserBasicInfo($user_id){
        if ($user_id==0 || $user_id=='' || $user_id==null)
            return [];

        $userInfo   =UserInfo::whereUserId($user_id)->first();
        $user       =User::whereId($user_id)->first();
        $result=[];
        if ($userInfo){
            $result['user_id']  =$userInfo->user_id;
            $result['email']    =$user ? $user->email : '';
            $result['nickname'] =$userInfo->nickname;
            $result['realname'] =$userInfo->realname;
            $result['company_name'] =$userInfo->company_name;
            $result['position'] =$userInfo->position;
            $result['sex']      =$userInfo->sex==0 ? '保密' : $userInfo->sex==1 ? '男' : '女';
            $result['photo_url']=FileManager::getImgUrl($userInfo->photo_id);
            if (!is_null($userInfo->province))
                $result['province']=$userInfo->province;
            else
                $result['province']='';

            if (!is_null($userInfo->city))
                $result['city']=$userInfo->city;
            else
                $result['city']='';

            if (!is_null($userInfo->area))
                $result['area']=$userInfo->area;
            else
                $result['area']='';

            if (!is_null($userInfo->address))
                $result['address']=$userInfo->address;
            else
                $result['address']='';

            //是否个人认证
            $result['is_personal_auth'] = self::isPersonalAuth($user_id);;

            //手机号
            $result['phone']       = $user ? $user->phone : '-';

            //是否单位认证
            $result['is_unit_auth'] = self::isUnitAuth($user_id);

            //是否专家认证
            $result['is_expert_auth'] = self::isExpert($user_id);

            //是否会员单位
            $result['is_member_unit'] = self::isVipUnitToUserId($user_id);

            //是否官方单位
            $result['is_official_unit'] = self::isOfficialUnitToUserId($user_id);

            //是否vip
            $result['is_vip'] = self::userWhetherVip($user_id);

            $isUnitAuth = self::isUnitAuth($user_id);
            if($isUnitAuth){
                /** @var UserXUnit $userXUnit */
                $userXUnit = UserXUnit::whereUserId($user_id)->first();
                if($userXUnit){
                    $unit = Units::whereId($userXUnit->unit_id)->whereIsMemberUnit(1)->first();
                    if($unit){
                        //单位名称
                        $result['unit_logo']    = FileManager::getImgUrl($unit->photo_id);
                        $result['unit_name']    = $unit->name;
                        $result['unit_contact']     = $unit->contact_number ? $unit->contact_number : $unit->contact_phone;
                        $result['unit_credit_code'] = $unit->uniform_social_credit_code;
                        $result['unit_label']       = UnitBusinessLabel::whereUnitId($unit->id)->pluck('name')->toArray();
                        $result['unit_province']    = $unit->province;
                        $result['unit_city']        = $unit->city;
                        $result['unit_area']        = $unit->area;
                        $result['unit_address']     = $unit->address;

                    } else {
                        $result['unit_name'] = '';
                    }
                }else{
                    $result['unit_name'] = '';
                }
            }else{
                $result['unit_name'] = '';
            }
        }
        return $result;
    }

    /**
     * 获取用户绑定的套餐
     * @param int $userId
     * @return array
     */
    public static function getUserBindVipPackageInfo($userId = 0){
        if(empty($userId))
            return [];

        $data = [];

        $userWhetherVip = VipInfo::whereUserId($userId)->whereStatus(1)->where('end_time','>',date('Y-m-d H:i:s',time()))->first();
        if($userWhetherVip){
            $userWhetherVip->vip_package_info = null;
            $vipPackageInfo = VipPackage::whereId($userWhetherVip->vip_package_id)->first();
            if($vipPackageInfo){
                $userWhetherVip->vip_package_info = $vipPackageInfo;
            }

            $userWhetherVip->bind_method = 1;
            $userWhetherVip->bind_method_name = '直接绑定';

            array_push($data,$userWhetherVip);
        }

        $unitAuth = self::isUnitAuth($userId);
        if($unitAuth){
            $userXUnit = UserXUnit::whereUserId($userId)->first();
            if($userXUnit){
                $userWhetherVipTwo = UnitBindVipPackage::whereUnitId($userXUnit->unit_id)->where('end_time','>',date('Y-m-d H:i:s',time()))->first();
                if($userWhetherVipTwo){
                    $userWhetherVipTwo->vip_package_info = null;
                    $vipPackageInfo = VipPackage::whereId($userWhetherVipTwo->vip_package_id)->first();
                    if($vipPackageInfo){
                        $userWhetherVipTwo->vip_package_info = $vipPackageInfo;
                    }

                    $userWhetherVipTwo->bind_method = 2;
                    $userWhetherVipTwo->bind_method_name = '继承会员单位';

                    array_push($data,$userWhetherVipTwo);
                }
            }
        }

        return $data;
    }

    /**\
     * 判断用户绑定的vip是否具有相关权益
     * @param int $vipRuleId
     * @param int $userId
     * @return bool
     */
    public static function judgeVipPackageXRule($vipRuleId = 0,$userId = 0){
        if(empty($vipRuleId) || empty($userId))
            return false;

        $isOfficialUnit = self::isOfficialUnitToUserId($userId);
        if($isOfficialUnit)
            return true;

        $vipRule = VipRule::whereId($vipRuleId)->first();
        if(!$vipRule)
            return false;

        $data = 0;
        $userBindVipPackageList = self::getUserBindVipPackageInfo($userId);
        if(count($userBindVipPackageList) > 0){
            foreach($userBindVipPackageList as $userBindVipPackage){
                if(!empty($userBindVipPackage->vip_package_info)){
                    $isVipLabel = VipPackageXRule::whereVipPackageId($userBindVipPackage->vip_package_info->id)->whereVipRuleId($vipRule->id)->first();
                    if($isVipLabel){
                        $data = 1;
                    }
                }
            }
        }

        if($data != 1)
            return false;

        return true;
    }

    /**
     * 是否个人认证
     * @param int $userId
     * @return bool
     */
    public static function isPersonalAuth($userId = 0){
        if(empty($userId))
            return -1;

        $isPersonalAuth = PersonalAuth::whereUserId($userId)->first();
        if(!$isPersonalAuth){
            return -1;
        }else{
            if($isPersonalAuth->is_auth == 1){
                return 1;
            }else{
                return 0;
            }
        }
    }

    /**
     * 是否单位认证
     * @param int $userId
     * @return bool
     */
    public static function isUnitAuth($userId = 0){
        if(empty($userId))
            return -1;

        $isUnitAuth = UnitAuth::whereUserId($userId)->first();
        if(!$isUnitAuth){
            return -1;
        }else{
            if($isUnitAuth->is_auth == 1){
                return 1;
            }else{
                return 0;
            }
        }
    }

    /**
     * 是否专家认证
     * @param int $userId
     * @return bool
     */
    public static function isExpert($userId = 0){
        if(empty($userId))
            return 0;

        $isExpert = Experts::whereUserId($userId)->whereIsAuth(1)->first();
        if(!$isExpert)
            return 0;

        return 1;
    }

    /**
     * 根据用户id是否会员单位
     * @param int $userId
     * @return int
     */
    public static function isVipUnitToUserId($userId = 0){
        if(empty($userId))
            return 0;

        $unitAuth = self::isUnitAuth($userId);
        if(!$unitAuth)
            return 0;

        /** @var UserXUnit $userXUnit */
        $userXUnit = UserXUnit::whereUserId($userId)->orderBy('created_at','desc')->first();
        if(!$userXUnit)
            return 0;

        $isunit = Units::whereId($userXUnit->unit_id)->whereIsMemberUnit(1)->first();
        if(!$isunit)
            return 0;

        return 1;
    }

    /**
     * 根据用户id是否官方单位
     * @param int $userId
     * @return int
     */
    public static function isOfficialUnitToUserId($userId = 0){
        if(empty($userId))
            return 0;

        $unitAuth = self::isUnitAuth($userId);
        if(!$unitAuth)
            return 0;

        /** @var UserXUnit $userXUnit */
        $userXUnit = UserXUnit::whereUserId($userId)->orderBy('created_at','desc')->first();
        if(!$userXUnit)
            return 0;

        $isunit = Units::whereId($userXUnit->unit_id)->whereIsMemberUnit(2)->first();
        if(!$isunit)
            return 0;

        return 1;
    }

    /**
     * 根据单位id判断是不是会员单位
     * @param int $unitId
     * @return int
     */
    public static function isVipUnitToUnitId($unitId = 0){
        if(empty($unitId))
            return 0;

        $isunit = Units::whereId($unitId)->whereIsMemberUnit(1)->first();
        if(!$isunit)
            return 0;

        return 1;
    }

    /**
     * 手机号格式验证
     * @param string $phone
     * @return bool
     */
    public static function phoneVerification($phone = ''){
        if(empty($phone))
            return false;

        if(!preg_match("/^(1[123456789])[0-9]{9}$/", trim($phone)))
            return false;

        return true;
    }

    /**
     * 信用代码正则
     * @param string $uniformSocialCreditCode
     * @return bool
     */
    public static function uniformSocialCreditCodeVerification($uniformSocialCreditCode = ''){
        if(empty($uniformSocialCreditCode))
            return false;

        if(!preg_match("/[0-9A-HJ-NPQRTUWXY]{2}\d{6}[0-9A-HJ-NPQRTUWXY]{10}/", trim($uniformSocialCreditCode)))
            return false;

        return true;
    }

    /**
     * 身份证号格式验证
     * @param string $idCard
     * @return bool
     */
    public static function idCardVerification($idCard = ''){
        if(empty($idCard))
            return false;

        if(!preg_match("/^[1-9]\d{5}(18|19|20|(3\d))\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/", trim($idCard)))
            return false;

        return true;
    }

    /**
     * 邮箱格式验证
     * @param string $email
     * @return bool
     */
    public static function emailVerification($email = ''){
        if(empty($email))
            return false;

        if(!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,})$/", trim($email)))
            return false;

        return true;
    }

    /**
     * 根据营业执照图片获取相应信息
     * @param int $imgId
     * @return bool|object
     */
    public static function getUnitInfoToImg($imgId = 0){
        if(empty($imgId))
            return false;

        /** @var Images $thisImage */
        $thisImage = Images::whereId($imgId)->first();
        if(!$thisImage)
            return false;

        /** @var Files $thisFile */
        $thisFile = Files::whereId($thisImage->file_id)->first();
        if(!$thisFile)
            return false;

        $fileContent = $thisFile->getContent();

        $image600px = Image::make($fileContent)->widen(2000)->encode($thisFile->file_ext);
        $file600px = FileManager::saveFileByFileContent($image600px->encoded, $thisFile->file_name . '-1000px.' . $thisFile->file_type, $image600px->mime(),"local");

        $FileBase64 = ToolsManager::base64EncodeImage($file600px->getLocalPath());

        $carBrandDiscern = new BusinessLicense();
        $result = $carBrandDiscern->businessLicenseIdentify($FileBase64);

        if(empty($result))
            return false;

        if(!empty($result->error_code))
            return false;


        if(empty($result->words_result))
            return false;

        $data = (object)[
            'a' => $result->words_result->单位名称->words,
            'b' => $result->words_result->社会信用代码->words,
            'c' => $result->words_result->法人->words,
            'd' => $result->words_result->注册资本->words,
            'e' => $result->words_result->成立日期->words,
            'f' => $result->words_result->地址->words,
            'g' => $result->words_result->经营范围->words,
            'h' => $result->words_result->类型->words,
            'i' => $result->words_result->有效期->words,
        ];

        return $data;
    }

    /**
     * 获取专家标签
     * @param int $expertId
     * @return array
     */
    public static function getExpertLabel($expertId = 0){
        if(empty($expertId))
            return [];

        $expertLabelArr = [];
        $expertLabelList = ExpertLabel::whereExpertId($expertId)->get();
        if(count($expertLabelList) > 0){
            foreach($expertLabelList as $expertLabel){
                array_push($expertLabelArr,$expertLabel->name);
            }
        }

        return $expertLabelArr;
    }

    /**
     * 获取专家资质图片
     * @param int $expertId
     * @return array
     */
    public static function getExpertQualificationImg($expertId = 0){
        if(empty($expertId))
            return [];

        $expertQualificationImgArr = [];
        $expertQualificationImgList = ExpertQualificationImg::whereExpertId($expertId)->get();
        if(count($expertQualificationImgList) > 0){
            foreach($expertQualificationImgList as $expertQualificationImg){
                $expertQualificationImgUrl = FileManager::getImgUrl($expertQualificationImg->img_id);

                $data = (object)['img_id' => $expertQualificationImg->img_id,'img_url' => $expertQualificationImgUrl];

                array_push($expertQualificationImgArr,$data);
            }
        }

        return $expertQualificationImgArr;
    }

    /**
     * 获取单位业务范围标签
     * @param int $unitId
     * @return array|bool
     */
    public static function getUnitBusinessLabel($unitId = 0){
        if(empty($unitId))
            return [];

        $unitBusinessLabelArr = [];
        $unitBusinessLabelList = UnitBusinessLabel::whereUnitId($unitId)->orWhere('unit_settled_apply_id',$unitId)->get();
        if(count($unitBusinessLabelList) > 0){
            foreach($unitBusinessLabelList as $unitBusinessLabel){
                array_push($unitBusinessLabelArr,$unitBusinessLabel->name);
            }
        }

        return $unitBusinessLabelArr;
    }

    /**
     * 获取单位的认证用户数量
     * @param int $unitId
     * @return int
     */
    public static function getUnitAuthNumToUnitId($unitId = 0,$isAdmin = 0){
        if(empty($unitId))
            return 0;

        $unit = Units::whereId($unitId)->first();
        if(!$unit)
            return 0;

        $unitEmployeeNum = UserXUnit::whereUnitId($unit->id)->whereIsAdmin($isAdmin)->count();

        return $unitEmployeeNum;
    }

    /**
     * 根据评论id获取评论点赞数量
     * @param int $commentId
     * @return int
     */
    public static function getCommentLikeNumToCommentId($commentId = 0){
        if(empty($commentId))
            return 0;

        $commentLikeNum = CommentLike::whereCommentId($commentId)->count();

        return $commentLikeNum;
    }

    /**
     * 获取评论
     * @param int $id
     * @param string $type
     * @param int $limit
     * @param int $page
     * @return Comment|array|null
     */
    public static function getCommentList($id = 0,$type = 'expert',$limit = 8,$page = 0,$user_id = 0){
        if($type == 'expert'){
            /** @var Comment $item */
            $comment = Comment::whereExpertId($id)->whereIsOfficial(1)->whereStatus(1)->whereType('expert')->orderBy('created_at','desc')->offset($limit * $page)->limit($limit)->get();
            if(count($comment) > 0){
                foreach($comment as $item){
                    $item->photo_url = url('images/default_logo.png');
                    $item->nickname  = "官方点评";

                    $item->comment_like_num = CommonManager::getCommentLikeNumToCommentId($item->id);
                }
            }

        }elseif($type == 'news'){
            /** @var Comment $val */
            $comment = Comment::whereNewsId($id)->whereStatus(1)->whereToCommentId(0)->whereType('news')->orderBy('is_official','desc')->orderBy('created_at','desc')->offset($limit * $page)->limit($limit)->get();
            if(count($comment) > 0){
                foreach($comment as $val){
                    $val->nickname = '';
                    $val->photo_url = '';

                    if($val->is_official == 1){
                        $val->photo_url = url('images/default_logo.png');
                        $val->nickname  = "官方点评";
                    }else{
                        $userInfo = self::getUserBasicInfo($val->user_id);
                        if($userInfo){
                            $val->nickname  = $userInfo['nickname'];
                            $val->photo_url = $userInfo['photo_url'];
                            $val->is_vip    = $userInfo['is_vip'];
                        }
                    }
                    $val->is_like   = self::userIsLikeComment($val->id,$user_id);
                    $val->comment_like_num = CommonManager::getCommentLikeNumToCommentId($val->id);

                    $replyList = Comment::whereToCommentId($val->id)->whereStatus(1)->get();
                    if(count($replyList) > 0){
                        foreach($replyList as $reply){
                            $reply->nickname  = '';
                            $reply->photo_url = '';
                            $reply->is_vip    = 0;
                            $userInfo = self::getUserBasicInfo($reply->user_id);
                            if($userInfo){
                                $reply->nickname  = $userInfo['nickname'];
                                $reply->photo_url = $userInfo['photo_url'];
                                $reply->is_vip    = $userInfo['is_vip'];
                            }

                            $reply->to_user_name = '';
                            $toUserInfo = self::getUserBasicInfo($reply->to_user_id);
                            if($toUserInfo){
                                $reply->to_user_name = $toUserInfo['nickname'];
                            }

                            $reply->is_like   = self::userIsLikeComment($reply->id,$user_id);
                            $reply->comment_like_num = CommonManager::getCommentLikeNumToCommentId($reply->id);
                        }
                    }

                    $val->reply_list = $replyList;
                }
            }
        }elseif($type == 'demand'){
            /** @var Comment $val */
            $comment = Comment::whereDemandId($id)->whereStatus(1)->whereToCommentId(0)->whereType('demand')->orderBy('is_official','desc')->orderBy('created_at','desc')->offset($limit * $page)->limit($limit)->get();
            if(count($comment) > 0){
                foreach($comment as $val){
                    $val->nickname = '';
                    $val->photo_url = '';

                    if($val->is_official == 1){
                        $val->photo_url = url('images/default_logo.png');
                        $val->nickname  = "官方点评";
                    }else{
                        $userInfo = self::getUserBasicInfo($val->user_id);
                        if($userInfo){
                            $val->nickname  = $userInfo['nickname'];
                            $val->photo_url = $userInfo['photo_url'];
                            $val->is_vip    = $userInfo['is_vip'];
                        }
                    }
                    $val->is_like   = self::userIsLikeComment($val->id,$user_id);
                    $val->comment_like_num = CommonManager::getCommentLikeNumToCommentId($val->id);

                    $replyList = Comment::whereToCommentId($val->id)->whereStatus(1)->get();
                    if(count($replyList) > 0){
                        foreach($replyList as $reply){
                            $reply->nickname  = '';
                            $reply->photo_url = '';
                            $reply->is_vip    = 0;
                            $userInfo = self::getUserBasicInfo($reply->user_id);
                            if($userInfo){
                                $reply->nickname  = $userInfo['nickname'];
                                $reply->photo_url = $userInfo['photo_url'];
                                $reply->is_vip    = $userInfo['is_vip'];
                            }

                            $reply->to_user_name = '';
                            $toUserInfo = self::getUserBasicInfo($reply->to_user_id);
                            if($toUserInfo){
                                $reply->to_user_name = $toUserInfo['nickname'];
                            }

                            $reply->is_like   = self::userIsLikeComment($reply->id,$user_id);
                            $reply->comment_like_num = CommonManager::getCommentLikeNumToCommentId($reply->id);
                        }
                    }

                    $val->reply_list = $replyList;
                }
            }
        }elseif($type == 'unit'){
            /** @var Comment $item */
            $comment = Comment::whereUnitId($id)->whereIsOfficial(1)->whereStatus(1)->whereType('unit')->orderBy('created_at','desc')->offset($limit * $page)->limit($limit)->get();
            if(count($comment) > 0){
                foreach($comment as $item){
                    $item->photo_url = url('images/default_logo.png');
                    $item->nickname  = "官方点评";

                    $item->comment_like_num = CommonManager::getCommentLikeNumToCommentId($item->id);
                }
            }
        }else{
            return [];
        }

        return $comment;
    }

    /**
     * 获取评论数量
     * @param int $id
     * @param string $type
     * @return int
     */
    public static function getCommentNum($id = 0,$type = 'expert'){
        if($type == 'expert'){
            $commentNum = Comment::whereExpertId($id)->whereIsOfficial(1)->whereStatus(1)->whereType('expert')->count();

        }elseif($type == 'news'){
            $commentNum = Comment::whereNewsId($id)->whereStatus(1)->whereType('news')->count();

        }elseif($type == 'unit'){
            $commentNum = Comment::whereUnitId($id)->whereIsOfficial(1)->whereStatus(1)->whereType('unit')->count();
        }else{
            return 0;
        }

        return $commentNum;
    }

    /**
     * 判断用户是否为该评论点赞
     * @param int $commentId
     * @param int $userId
     * @return int
     */
    public static function userIsLikeComment($commentId = 0,$userId = 0){
        if(empty($commentId))
            return 0;

        $commentLike = CommentLike::whereCommentId($commentId)->whereUserId($userId)->first();
        if(!$commentLike)
            return 0;

        return 1;
    }

    /**
     * 获取评论详情
     * @param int $id
     * @param string $type
     * @return Comment|null
     */
    public static function getCommentDetail($id = 0,$type = 'expert',$userId = 0){
        if($type == 'expert'){
            /** @var Comment $comment */
            $comment = Comment::whereId($id)->whereIsOfficial(1)->whereStatus(1)->whereType('expert')->first();
            if($comment){
                $comment->photo_url = url('images/default_logo.png');
                $comment->nickname  = "官方点评";
                $comment->is_like   = self::userIsLikeComment($comment->id,$userId);
                $comment->comment_like_num = self::getCommentLikeNumToCommentId($comment->id);
            }

        }elseif($type == 'news'){
            /** @var Comment $comment */
            $comment = Comment::whereId($id)->whereStatus(1)->whereType('news')->first();
            if($comment){
                $comment->nickname = '';
                $comment->photo_url = '';

                if($comment->is_official == 1){
                    $comment->photo_url = url('images/default_logo.png');
                    $comment->nickname  = "官方点评";
                }else{
                    $userInfo = self::getUserBasicInfo($comment->user_id);
                    if($userInfo){
                        $comment->nickname = $userInfo['nickname'];
                        $comment->photo_url = $userInfo['photo_url'];
                    }
                }

                $comment->comment_like_num = self::getCommentLikeNumToCommentId($comment->id);
            }
        }elseif($type == 'unit'){
            /** @var Comment $comment */
            $comment = Comment::whereId($id)->whereIsOfficial(1)->whereStatus(1)->whereType('unit')->first();
            if($comment){
                $comment->photo_url = url('images/default_logo.png');
                $comment->nickname  = "官方点评";
                $comment->is_like   = self::userIsLikeComment($comment->id,$userId);
                $comment->comment_like_num = self::getCommentLikeNumToCommentId($comment->id);
            }
        }else{
            return null;
        }

        return $comment;
    }

    /**
     * 获取活动未读消息数量
     * @param int $userId
     * @return int
     */
    public static function getActivityMessageNum($userId = 0){
        if(empty($userId))
            return 0;

        $messageIdArr = Message::whereToUserId($userId)->whereType('activity')->pluck('id');

        $messageRemind = MessageRemind::whereIn('message_id',$messageIdArr)->whereUserId($userId)->count();

        return $messageRemind;
    }

    /**
     * 获取需求未读消息数量
     * @param int $userId
     * @return int
     */
    public static function getDemandMessageNum($userId = 0){
        if(empty($userId))
            return 0;

        $messageIdArr = Message::whereToUserId($userId)->whereType('demand')->pluck('id');

        $messageRemind = MessageRemind::whereIn('message_id',$messageIdArr)->whereUserId($userId)->count();

        return $messageRemind;
    }

    /**
     * 获取系统消息未读数量
     * @param int $userId
     * @return int
     */
    public static function getSystemMessageNum($userId = 0){
        if(empty($userId))
            return 0;

        $messageIdArr = Message::whereType('system')->pluck('id');

        $messageRemind = MessageRemind::whereIn('message_id',$messageIdArr)->whereUserId($userId)->count();

        return $messageRemind;
    }

    /**
     * 获取我关注的需求数量
     * @param int $userId
     * @return int
     */
    public static function getUserAttentionDemandNum($userId = 0){
        if(empty($userId))
            return 0;

        $userAttentionDemandNum = UserAttentionDemand::whereUserId($userId)->count();

        return $userAttentionDemandNum;
   }

    /**
     * 获取我关注的资讯数量
     * @param int $userId
     * @return int
     */
    public static function getUserAttentionNewsNum($userId = 0){
        if(empty($userId))
            return 0;

        $userAttentionNewsNum = UserAttentionNews::whereUserId($userId)->count();

        return $userAttentionNewsNum;
    }

    /**
     * 获取我关注的活动数量
     * @param int $userId
     * @return int
     */
    public static function getUserAttentionActivityNum($userId = 0){
        if(empty($userId))
            return 0;

        $userAttentionActivityNum = UserAttentionActivity::whereUserId($userId)->count();

        return $userAttentionActivityNum;
    }

    /**
     * 获取我发布的需求数量
     * @param int $userId
     * @return int
     */
    public static function getUserReleaseDemandNum($userId = 0){
        if(empty($userId))
            return 0;

//        $userReleaseDemandNum = Demands::whereUserId($userId)->whereIsShop(1)->whereReview(1)->count();
        $userReleaseDemandNum = Demands::whereUserId($userId)->count();

        return $userReleaseDemandNum;
    }

    /**
     * 获取我对接的需求数量
     * @param int $userId
     * @return int
     */
    public static function getUserButtDemandNum($userId = 0){
        if(empty($userId))
            return 0;

        $userButtDemandNum = DemandButt::whereUserId($userId)->count();

        return $userButtDemandNum;
    }

    /**
     * 我参与的活动数量
     * @param int $userId
     * @return int
     */
    public static function getUserJoinActivityNum($userId = 0){
        if(empty($userId))
            return 0;

        $ActivityJoinIds = ActivityJoin::whereUserId($userId)->whereStatus(1)->pluck('activity_id');

        $activityNum = Activity::whereIn('id',$ActivityJoinIds)->whereStatus(1)->count();

        return $activityNum;
    }

    /**
     * 获取活动参与数量
     * @param int $activityId
     * @return int
     */
    public static function getActivityJoinNum($activityId = 0){
        if(empty($activityId))
            return 0;

        $ActivityJoinNum = ActivityJoin::whereActivityId($activityId)->whereStatus(1)->count();

        return $ActivityJoinNum;
    }

    /**
     * 获取活动房信息
     * @param int $id
     * @return ActiveParty|\Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|int|null
     */
    public static function getActivePartyInfo($id = 0){
        if(empty($id))
            return null;

        $activeParty = ActiveParty::whereId($id)->first();
        if($activeParty){
            $activeParty->logo_url = FileManager::getImgUrl($activeParty->logo_id);

            if($activeParty->type == 1){
                $activeParty->type_name = '官方';
            }else{
                $activeParty->type_name = '非官方';
            }
        }

        return $activeParty;
    }

    /**
     * 获取活动列表
     * @param string $type
     * @param int $limit
     * @param int $page
     * @param string $keyword
     * @param int $activePartyId
     * @param int $status
     * @param int $isShow
     * @param User|null $user
     * @param int $id
     * @return mixed
     */
    public static function getActivityList($type = 'list',$limit = 10,$page = 0,$keyword = '',$isOfficial = '',$activePartyId = 0,$status = 0,$isShow = 0,User $user = null,$id = 0,$unitId = 0){
        if($type == 'list'){
            /** @var Activity $activity */
            if(is_array($id) && count($id) > 0){
                $activityList = Activity::whereIn('id',$id)->whereNull('deleted_at');
            }else{
                $activityList = Activity::whereNull('deleted_at');
            }

            if($keyword != ''){
                $activityList->where('name','like','%'.trim($keyword).'%');
            }

            if($isOfficial !== ''){
                $activePartyIds = ActiveParty::whereType($isOfficial)->pluck('id');

                $activityList = $activityList->whereIn('active_party_id',$activePartyIds);
            }

            if($activePartyId != 0){
                $activityList = $activityList->whereActivePartyId($activePartyId);
            }

            //当前时间
            $time = date('Y-m-d H:i:s',time());

            //报名中
            if($status == 1){
                $activityList = $activityList->where('start_time','>',$time);
            }

            //进行中
            if($status == 2){
                $activityList = $activityList->where('end_time','>',$time)->where('start_time','<=',$time);
            }

            //已结束
            if($status == 3){
                $activityList = $activityList->where('end_time','<',$time);
            }

            if($isShow != 0){
                $activityList = $activityList->whereStatus(1);
            }

            $pageInfo['total'] = $activityList->count();

            $activityList = $activityList->orderBy('created_at','desc')->offset($limit * $page)->limit($limit)->get();
            if(count($activityList) > 0){
                foreach($activityList as $activity){
                    $activity->activity_Join_num = self::getActivityJoinNum($activity->id);
                    $activity->img_url = FileManager::getImgUrl($activity->img_id);
                    $activity->week    = date("W",strtotime($activity->start_time));
                    $activity->share_img_url = FileManager::getImgUrl($activity->share_img_id);
                    $activity->sign_img_url = FileManager::getImgUrl($activity->sign_qr_code_img_id);
                    if($time < $activity->start_time){
                        $conduct = '报名中';
                        $activityStatus = 1;
                    }elseif($time > $activity->end_time){
                        $conduct = '已结束';
                        $activityStatus = 3;
                    }else{
                        $conduct = '进行中';
                        $activityStatus = 2;
                    }
                    $activity->activity_status = $activityStatus;
                    $activity->activity_status_name = $conduct;

                    $activeParty = self::getActivePartyInfo($activity->active_party_id);
                    $activity->active_party_Info = $activeParty;

                    $activity->activity_url = '/pages/details/activityDetail/activityDetail?activityId=' . $activity->id;

                    if($user){
                        /** @var ActivityJoin $thisJoinActivity */
                        $thisJoinActivity = ActivityJoin::whereUserId($user->id)->whereActivityId($activity->id)->whereStatus(1)->first();
                        if($thisJoinActivity){
                            $activity->is_join = 1;
                        }else{
                            $activity->is_join = 2;
                        }

                        $thisUserCollection = UserAttentionActivity::whereUserId($user->id)->whereActivityId($activity->id)->first();
                        if($thisUserCollection){
                            $activity->is_collection = 1;
                        }else{
                            $activity->is_collection = 2;
                        }
                    }else{
                        $activity->is_join       = null;
                        $activity->is_collection = null;

                    }

                    $activity->is_open_invoice = 0;
                    $invoiceRecord = InvoiceRecord::whereActivityId($activity->id)->whereUnitId($unitId)->first();
                    if($invoiceRecord){
                        $activity->is_open_invoice = 1;
                    }
                }
            }

            return $activityList;
        }elseif($type == 'detail'){
            /** @var Activity $activity */
            $activity = Activity::whereId($id);

            if($isShow != 0) {
                $activity->whereStatus(1);
            }

            $activity = $activity->first();
            if($activity){
                $activity->activity_Join_num = self::getActivityJoinNum($activity->id);
                $activity->img_url   = FileManager::getImgUrl($activity->img_id);
                $activity->week    = date("W",strtotime($activity->start_time));
                $activity->share_img_url = FileManager::getImgUrl($activity->share_img_id);
                $activity->sign_img_url = FileManager::getImgUrl($activity->sign_qr_code_img_id);
                //当前时间
                $time = date('Y-m-d H:i:s',time());

                if($time < $activity->start_time){
                    $conduct = '报名中';
                    $activityStatus = 1;
                }elseif($time > $activity->end_time){
                    $conduct = '已结束';
                    $activityStatus = 3;
                }else{
                    $conduct = '进行中';
                    $activityStatus = 2;
                }
                $activity->activity_status = $activityStatus;
                $activity->activity_status_name = $conduct;

                $activeParty = self::getActivePartyInfo($activity->active_party_id);
                $activity->active_party_Info = $activeParty;

                $activity->activity_url = '/pages/details/activityDetail/activityDetail?activityId=' . $activity->id;

                if($user){
                    /** @var ActivityJoin $thisJoinActivity */
                    $thisJoinActivity = ActivityJoin::whereUserId($user->id)->whereActivityId($activity->id)->whereStatus(1)->first();
                    if($thisJoinActivity){
                        $activity->is_join = 1;
                    }else{
                        $activity->is_join = 2;
                    }

                    $thisUserCollection = UserAttentionActivity::whereUserId($user->id)->whereActivityId($activity->id)->first();
                    if($thisUserCollection){
                        $activity->is_collection = 1;
                    }else{
                        $activity->is_collection = 2;
                    }
                }else{
                    $activity->is_join       = null;
                    $activity->is_collection = null;

                }

                $signUpTAble = json_decode($activity->sign_up_table);
                $signUpTAbleArr = [];

                if(is_array($signUpTAble) && in_array('realname',$signUpTAble)){
                    $realname = (object)[
                        'name'  => '姓名',
                        'value' => 'realname',
                        'input' => ''
                    ];
                    array_push($signUpTAbleArr,$realname);
                }

                if(is_array($signUpTAble) && in_array('phone',$signUpTAble)) {
                    $phone = (object)[
                        'name'  => '手机',
                        'value' => 'phone',
                        'input' => ''
                    ];
                    array_push($signUpTAbleArr,$phone);
                }

                if(is_array($signUpTAble) && in_array('company',$signUpTAble)){
                    $company = (object)[
                        'name'  => '公司',
                        'value' => 'company',
                        'input' => ''
                    ];
                    array_push($signUpTAbleArr,$company);
                }

                if(is_array($signUpTAble) && in_array('position',$signUpTAble)){
                    $position = (object)[
                        'name'  => '岗位',
                        'value' => 'position',
                        'input' => ''
                    ];
                    array_push($signUpTAbleArr,$position);
                }

                if(is_array($signUpTAble) && in_array('email',$signUpTAble)){
                    $email = (object)[
                        'name'  => '邮箱',
                        'value' => 'email',
                        'input' => ''
                    ];
                    array_push($signUpTAbleArr,$email);
                }

                if(is_array($signUpTAble) && in_array('remark',$signUpTAble)){
                    $remark = (object)[
                        'name'  => '备注',
                        'value' => 'remark',
                        'input' => ''
                    ];
                    array_push($signUpTAbleArr,$remark);
                }

                $activity->sign_up_table = $signUpTAbleArr;

            }

            return $activity;
        }else{
            return null;
        }
    }

    /**
     * 获取活动数量
     * @param string $keyword
     * @param int $activePartyId
     * @param int $status
     * @param int $isShow
     * @return mixed
     */
    public static function getActivityNum($keyword = '',$activePartyId = 0,$status = 0,$isShow = 0){
        $activityNum = Activity::whereNull('deleted_at');

        if($keyword != ''){
            $activityNum->where('name','like','%'.trim($keyword).'%');
        }

        if($activePartyId != 0){
            $activityNum = $activityNum->whereActivePartyId($activePartyId);
        }

        //当前时间
        $time = date('Y-m-d H:i:s',time());

        //报名中
        if($status == 1){
            $activityNum = $activityNum->where('start_time','>',$time);
        }

        //进行中
        if($status == 2){
            $activityNum = $activityNum->where('end_time','>',$time)->where('start_time','<=',$time);
        }

        //已结束
        if($status == 3){
            $activityNum = $activityNum->where('end_time','<',$time);
        }

        if($isShow != 0){
            $activityNum = $activityNum->whereStatus(1);
        }

        $activityNum = $activityNum->count();

        return $activityNum;
    }

    /**
     * 根据用户id获取个人认证信息
     * @param int $userId
     * @return PersonalAuth|\Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|null
     */
    public static function getPersonalAuthInfo($userId = 0){
        if(empty($userId))
            return null;

        $personalAuth = PersonalAuth::whereUserId($userId)->whereIsAuth(1)->first();
        if($personalAuth){
            $personalAuth->work_img_url = FileManager::getImgUrl($personalAuth->work_img_id);

            $personalAuth->is_member_unit = self::isVipUnitToUserId($userId);
        }

        return $personalAuth;
    }

    /**
     * 获取用户认证的单位信息
     * @param int $userId
     * @return Units|\Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|null
     */
    public static function getUnitInfo($userId = 0){
        if(empty($userId))
            return null;

        $unitAuth = self::isUnitAuth($userId);
        if(!$unitAuth)
            return null;

        /** @var UserXUnit $userXUnit */
        $userXUnit = UserXUnit::whereUserId($userId)->first();
        if(!$userXUnit)
            return null;

        $unitInfo = Units::whereId($userXUnit->unit_id)->whereIsMemberUnit(1)->first();
        if($unitInfo){
            $unitInfo->logo_url = FileManager::getImgUrl($unitInfo->photo_id);

            $unitInfo->license_img_url = FileManager::getImgUrl($unitInfo->license_img_id);
        }

        return $unitInfo;
    }

    /**
     * 获取认证审核状态
     * @param int $status
     * @return string
     */
    public static function getAuthReviewStatus($status = 0){
        switch($status){
            case 0:
                $result = '待处理';
                break;
            case 1:
                $result = '通过';
                break;
            case 2:
                $result = '拒绝';
                break;
            case 3:
                $result = '注销';
                break;
            default:
                $result = '未知';
                break;
        }

        return $result;
    }

    /**
     * 获取单位列表
     * @param string $type
     * @param int $isMemberUnit
     * @param string $keyword
     * @param int $limit
     * @param int $page
     * @param int $id
     * @return Units|\Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|null
     */
    public static function getAllUnitInfoList($type ='list',$isMemberUnit = 0,$keyword = '',$limit = 8,$page = 0,$id = 0,$user_id = 0,$classifyId = 0,$unitGradeId = 0){
        if($type == 'list'){
            /** @var Units $unit */
            if(!empty($user_id)){
                $unitList = Units::whereId($user_id)->whereIsMemberUnit($isMemberUnit);
            }else{
                $unitList = Units::whereIsMemberUnit($isMemberUnit);
            }

            if($keyword != ''){
                $unitList->where('name','like','%'.trim($keyword).'%');
            }

            if($classifyId != 0){
                $unitList->whereClassifyId($classifyId);
            }

            if($unitGradeId != 0){
                $unitList->whereUnitGradeId($unitGradeId);
            }

            $unitList = $unitList->orderBy('sort','asc')->orderBy('created_at','desc')->offset($limit * $page)->limit($limit)->get();
            if(count($unitList) > 0){
                foreach($unitList as $unit){
                    $unit->logo_url        = FileManager::getImgUrl($unit->photo_id);
                    $unit->license_img_url = FileManager::getImgUrl($unit->license_img_id);
                    $unit->auth_employeeNum_num   = self::getUnitAuthNumToUnitId($unit->id,0);
                    $unit->auth_admin_num   = self::getUnitAuthNumToUnitId($unit->id,1);
                    $unit->vip_package_name = '无';
                    $unit->introduction = strip_tags($unit->introduction);
                    $unitBindVipPackage = UnitBindVipPackage::whereUnitId($unit->id)->where('end_time','>',date('Y-m-d H:i:s',time()))->first();
                    if($unitBindVipPackage){
                        $vipPackage = VipPackage::whereId($unitBindVipPackage->vip_package_id)->first();
                        if($vipPackage){
                            $unit->vip_package_name = $vipPackage->name;
                        }
                    }

                    if($unit->is_member_unit == 1){
                        $unit->unit_url        = '/pages/memberUnit/MemberDetail/MemberDetail?memberId=' . $unit->id;
                    }

                    $unit->classify_Info   = null;
                    $unit->unit_grade_Info = null;

                    $classify = Classify::whereId($unit->classify_id)->first();
                    if($classify){
                        $unit->classify_Info = $classify;
                    }

                    $unitGrade = UnitGrade::whereId($unit->unit_grade_id)->first();
                    if($unitGrade){
                        $unit->unit_grade_Info = $unitGrade;
                    }
                }
            }

            return $unitList;
        }elseif($type == 'detail'){
            if(empty($id))
                return null;

            $memberUnit = Units::whereId($id)->first();

            if($memberUnit){
                $official_comment_ids = Comment::whereUnitId($memberUnit->id)->whereIsOfficial(1)->pluck('id')->toArray();
                $official_comment_arr=[];
                if (count($official_comment_ids) > 0){
                    foreach ($official_comment_ids as $comment_id){
                        $temp=self::getCommentDetail($comment_id,'unit',$user_id);
                        if ($temp)
                            array_push($official_comment_arr,$temp);
                    }
                }
                $memberUnit->logo_url             = FileManager::getImgUrl($memberUnit->photo_id);
                $memberUnit->unit_business_label  = CommonManager::getUnitBusinessLabel($memberUnit->id);
                $memberUnit->license_img_url      = FileManager::getImgUrl($memberUnit->license_img_id);
                $memberUnit->unit_url             = 'jiojoijioage';
                $memberUnit->official_comment     = $official_comment_arr;
                $memberUnit->classify_name = '';
                $memberUnit->unit_grade_name = '';

                $classify = Classify::whereId($memberUnit->classify_id)->first();
                if($classify){
                    $memberUnit->classify_name = $classify->name;
                }

                $unitGrade = UnitGrade::whereId($memberUnit->unit_grade_id)->first();
                if($unitGrade){
                    $memberUnit->unit_grade_name = $unitGrade->name;
                }

                if($memberUnit->is_member_unit == 1){
                    $memberUnit->unit_url        = '/pages/memberUnit/MemberDetail/MemberDetail?memberId=' . $memberUnit->id;
                }

                $memberUnit->classify_Info   = null;
                $memberUnit->unit_grade_Info = null;

                $classify = Classify::whereId($memberUnit->classify_id)->first();
                if($classify){
                    $memberUnit->classify_Info = $classify;
                }

                $unitGrade = UnitGrade::whereId($memberUnit->unit_grade_id)->first();
                if($unitGrade){
                    $memberUnit->unit_grade_Info = $unitGrade;
                }

                $UnitUserIds = [];
                $userXUnits = UserXUnit::whereUnitId($memberUnit->id)->get();
                if(count($userXUnits) > 0){
                    foreach($userXUnits as $userXUnit){
                        array_push($UnitUserIds,$userXUnit->user_id);
                    }
                }

                $demandCount = Demands::whereIn('user_id',$UnitUserIds)->whereUnitId($memberUnit->id)->whereReview(1)->count();
                $demandIds   = Demands::whereIn('user_id',$UnitUserIds)->whereUnitId($memberUnit->id)->whereReview(1)->pluck('id');

                $memberUnit->demand_count = $demandCount;

                $successButtCount = DemandButt::whereIn('user_id',$UnitUserIds)->whereUnitId($memberUnit->id)->whereStatus(1)->count();

                $successButtCount2 = DemandButt::whereIn('demand_id',$demandIds)->whereStatus(1)->count();

                $memberUnit->demand_success_butt_count = $successButtCount + $successButtCount2;
            }

            return $memberUnit;
        }else{
            return null;
        }
    }

    /**
     * 获取单位数量
     * @param int $isMemberUnit
     * @param string $keyword
     * @return mixed
     */
    public static function getAllUnitInfoNum($isMemberUnit = 0,$keyword = ''){
        if($keyword != '') {
            $unitList = Units::whereIsMemberUnit($isMemberUnit)->where('name','like','%'.trim($keyword).'%')->count();
        }else{
            $unitList = Units::whereIsMemberUnit($isMemberUnit)->count();
        }

        return $unitList;
    }

    /**
     * 获取专家列表
     * @param string $type
     * @param string $keyword
     * @param int $limit
     * @param int $page
     * @param string $isAuth
     * @param int $id
     * @return Experts|bool|\Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|null
     */
    public static function getExpertInfoList($showType = 'backstage',$type = 'list',$keyword = '',$limit = 10,$page = 0,$isAuth = '',$id = 0,$user_id = 0){
        if($type == 'list'){
            /** @var Experts $expert */
            if($showType == 'backstage'){
                $expertList = Experts::whereIn('is_auth',[1,3]);

                if($isAuth != ''){
                    $expertList = $expertList->whereIsAuth($isAuth);
                }
            }else{
                $expertList = Experts::whereIsAuth(1);
            }

            if($keyword != ''){
                $userId = User::where('phone','like','%'.trim($keyword).'%')->pluck('id');

                $userIds = UserInfo::whereIn('user_id',$userId)->orWhere('nickname','like','%'.trim($keyword).'%')->pluck('user_id');

                $expertList->whereIn('user_id',$userIds)->orWhere('realname','like','%'.trim($keyword).'%');
            }

            $pageInfo['total'] = $expertList->count();

            $expertList = $expertList->orderBy('created_at','desc')->offset($limit * $page)->limit($limit)->get();
            if(count($expertList) > 0){
                foreach($expertList as $expert){
                    $thePhone = "-";
                    $userBasicInfo = CommonManager::getUserBasicInfo($expert->user_id);
                    if(is_null($expert->phone) || trim($expert->phone) == ""){
                        if(count($userBasicInfo) > 0 && isset($userBasicInfo['phone'])){
                            $expert->phone = $userBasicInfo['phone'];
                        }
                    }
                    $expert->photo_url    = FileManager::getImgUrl($expert->photo_id);
                    $expert->expert_label = self::getExpertLabel($expert->id);
                    $expert->auth_status  = self::getAuthReviewStatus($expert->is_auth);
                }
            }

            return $expertList;
        }elseif($type == 'detail'){
            $expert = Experts::whereId($id)->first();
            if($expert){
                $userBasicInfo = CommonManager::getUserBasicInfo($expert->user_id);
                $expert->phone        = $expert->phone ? $expert->phone : $userBasicInfo ? $userBasicInfo['phone'] : '';
                $expert->photo_url = FileManager::getImgUrl($expert->photo_id);

                $expert->expert_label = self::getExpertLabel($expert->id);
                $official_comment_ids = Comment::whereExpertId($expert->id)->whereIsOfficial(1)->pluck('id')->toArray();
                $official_comment_arr=[];
                if (count($official_comment_ids) > 0){
                    foreach ($official_comment_ids as $comment_id){
                        $temp=self::getCommentDetail($comment_id,'expert',$user_id);
                        if ($temp)
                            array_push($official_comment_arr,$temp);
                    }
                }

                $expert->expert_qualification_img   = self::getExpertQualificationImg($expert->id);
                $expert->auth_status                = self::getAuthReviewStatus($expert->is_auth);
                $expert->official_comment           = $official_comment_arr;
                $expert->is_appointed               = AppointExpert::whereExpertId($expert->id)->whereUserId($user_id)->whereStatus(0)->first() ? 1 :0;
            }

            return $expert;
        }else{
            return false;
        }
    }

    /**
     * 获取专家数量
     * @param string $keyword
     * @param string $isAuth
     * @return mixed
     */
    public static function getExpertInfoDNum($keyword = '',$isAuth = ''){
        /** @var Experts $expert */
        $expertList = Experts::whereIn('is_auth',[1,3]);

        if($keyword != ''){
            $expertList->where('realname','like','%'.trim($keyword).'%');
        }

        if($isAuth != ''){
            $expertList = $expertList->whereIsAuth($isAuth);
        }

        $expertNum = $expertList->count();

        return $expertNum;
    }

    /**
     * 判断vip套餐是否正在被使用
     * @param int $id
     * @return int
     */
    public static function vipPackageWhetherUse($id = 0){
        if(empty($id))
            return 0;

        $vipPackageWhetherUse = VipInfo::whereVipPackageId($id)->whereStatus(1)->where('end_time','>',date('Y-m-d H:i:s',time()))->first();
        if(!$vipPackageWhetherUse){
            $vipPackageWhetherUse = UnitBindVipPackage::whereVipPackageId($id)->where('end_time','>',date('Y-m-d H:i:s',time()))->first();
            if(!$vipPackageWhetherUse){
                return 0;
            }
        }

        return 1;
    }

    /**
     * 判断用户是否是vip
     * @param int $userId
     * @return int
     */
    public static function userWhetherVip($userId = 0){
        if(empty($userId))
            return 0;

        $userWhetherVip = VipInfo::whereUserId($userId)->whereStatus(1)->where('end_time','>',date('Y-m-d H:i:s',time()))->first();
        if(!$userWhetherVip){
            $unitAuth = self::isUnitAuth($userId);
            if($unitAuth){
                $userXUnit = UserXUnit::whereUserId($userId)->first();
                if($userXUnit){
                    $userWhetherVip = UnitBindVipPackage::whereUnitId($userXUnit->unit_id)->where('end_time','>',date('Y-m-d H:i:s',time()))->first();
                    if(!$userWhetherVip){
                        return 0;
                    }
                }else{
                    return 0;
                }
            }else{
                return 0;
            }
        }

        return 1;
    }

    public static function getPublishTime($the_time){
/*        //现在时间
        $now_time       = date("Y-m-d H:i:s",time());
        $now_year       = date('Y',time());
        $now_Hour       = date('H',time());
        //过去时间
        $pass_1_day     = self::getPassTime(1);
        $pass_7_day     = self::getPassTime(7);
        $hour=1;
        $pass_1_hour    = date('Y-m-d H:i:s',strtotime("$now_time - $hour  hour"));
        if (date_format($created_at,'Y') ==$now_year){
            //七天前
            if ($created_at < $pass_7_day){
                return date_format($created_at,'n-j');
            } else if ($created_at < $pass_1_day){
                //七天内，一天前
                $public_Time_Day=date_format($created_at,'d');
                return date('j天前',strtotime("$now_time - $public_Time_Day days"));
            } else {
                //一天内
                if ($created_at < $pass_1_hour){
                    //一小时前
                    $public_Time_Hour=date_format($created_at,'H');
                    return date('G小时前',strtotime("$now_time - $public_Time_Hour hours"));
                } else {
                    //一小时内
                    $public_Time_Min=date_format($created_at,'i');
                    $min=date('i',strtotime("$now_time - $public_Time_Min minutes"));
                    return intval($min).'分钟前';
                }
            }
        } else {
            return date_format($created_at,'Y-m-d');
        }*/

        $now_time = date("Y-m-d H:i:s", time());
        $now_year       = date('Y',time());
        //echo $now_time;
        $now_time = strtotime($now_time);
        $show_time = strtotime($the_time);
        $dur = $now_time - $show_time;
        if ($dur < 0) {
            return $the_time;
        } else {
            if ($dur < 60) {
                return $dur . '秒前';
            } else {
                if ($dur < 3600) {
                    return floor($dur / 60) . '分钟前';
                } else {
                    if ($dur < 86400) {
                        return floor($dur / 3600) . '小时前';
                    } else {
                        if ($dur < (24*60*60*7)) {//7天内
                            return floor($dur / 86400) . '天前';
                        } else  if (date_format($the_time,'Y') !=$now_year){
                            return $the_time;
                        } else {
                            return date_format($the_time,'n-j');
                        }
                    }
                }
            }
        }

    }
    public static function getPassTime($passDay=10){
        $todayTime = date("Y-m-d H:i:s",time());
//        $passDay=$passDay;
        //若干天之前的时间
        $lastTime   = date('Y-m-d H:i:s',strtotime("$todayTime - $passDay days"));
        return $lastTime;
    }

    /**
     * 活动浏览记录
     * @param int $activityId
     * @param int $userId
     */
    public static function activityBrowseRecord($activityId = 0,$userId = 0,$ip = ''){
        /** @var Activity $activity */
        $activity = Activity::whereId($activityId)->whereStatus(1)->first();
        if($activity){
            /** @var ActivityBrowseRecord $thisActivityBrowseRecord */
            $thisActivityBrowseRecord = ActivityBrowseRecord::whereActivityId($activity->id)->whereUserId($userId)->orderBy('created_at','desc')->first();
            if($thisActivityBrowseRecord){
                if(strtotime($thisActivityBrowseRecord->created_at) + 300 <= time()){
                    $newActivityBrowseRecord = new ActivityBrowseRecord();
                    $newActivityBrowseRecord->user_id       = $userId;
                    $newActivityBrowseRecord->activity_id   = $activity->id;
                    $newActivityBrowseRecord->ip            = $ip;
                    $newActivityBrowseRecord->save();

                    $activity->browse_num += 1;
                    $activity->save();
                }
            }else{
                $newActivityBrowseRecord = new ActivityBrowseRecord();
                $newActivityBrowseRecord->user_id       = $userId;
                $newActivityBrowseRecord->activity_id   = $activity->id;
                $newActivityBrowseRecord->ip            = $ip;
                $newActivityBrowseRecord->save();

                $activity->browse_num += 1;
                $activity->save();
            }
        }
    }

}
